<?php

/**
 * myphotos actions.
 *
 * @package    sf_sandbox
 * @subpackage myphotos
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
 */
class myphotosActions extends sfActions {
	/**
	 * Executes index action
	 *
	 * @param sfRequest $request A request object
	 */
	public function executeIndex(sfWebRequest $request) {
		if (! $request->getParameter ( 'page' )) {
			$this->page = 1;
		} else {
			$this->page = $request->getParameter ( 'page' );
		}
		
		$c = new Criteria ( );
		$c->add ( GroupgalleryPeer::USER_ID, $this->getUser ()->getAttribute ( 'user_id', null, 'sfGuardSecurityUser' ) );
		$pager = new sfPropelPager ( 'Groupgallery', sfConfig::get ( 'app_group_gallery_perpage' ) );
		$pager->setCriteria ( $c );
		$pager->setPeerMethod ( 'doSelect' );
		$pager->setPage ( $this->page );
		$pager->init ();
		$this->gallery = $pager;
		
		///Кидаем пользователя в layout
	     $this->getRequest()->setAttribute('v', $this->getUser()->getProfile());
		////
	}
	
	public function executeAddgallery(sfWebRequest $request) {
		
		$this->setDecorator();
		if ($this->getUser ()->getProfile ()->getGender () == 'm') {
			
			$now = new sfDate ( );
			$g = new Groupgallery ( );
			$g->setUserId ( $this->getUser ()->getAttribute ( 'user_id', null, 'sfGuardSecurityUser' ) );
			////Автоутверждение галереи
				if(sfConfig::get('app_gallery_autoapprove')=='true')
				{
					$g->setPub ( 3 );
				}
				else 
				{
				$g->setDateExpire ( $now->addDay ( 30 )->dump () );
				$g->setPub ( 1 );
				}
			$g->setLogoId ( 1 );
			$g->setCount ( 0 );
			$c = new Criteria ( );
			$c->add ( GroupgalleryPeer::USER_ID, $this->getUser ()->getAttribute ( 'user_id', null, 'sfGuardSecurityUser' ) );
			$cnt = GroupgalleryPeer::doCount ( $c );
			if ($cnt == 0) {
				$g->setMaxPhotos ( sfConfig::get('app_first_gallery_max') );
				$g->setType ( false );
				$g->save ();
			} else {
				$u = $this->getUser ()->getProfile ();
				if ($u->getAccount () < sfConfig::get ( 'app_cost_gallery_add' ) and sfConfig::get('app_use_payment_show_gallery')==true) {
					$this->getUser ()->setFlash ( 'error', 'У вас недостаточно средств на счете' );
					$this->redirect ( '@account' );
				} else {
					
					$g->setMaxPhotos ( sfConfig::get('app_last_gallery_max') );
					$g->setType ( true );
					$c = new Criteria ( );
					$c->add ( GroupgalleryPeer::USER_ID, $this->getUser ()->getAttribute ( 'user_id', null, 'sfGuardSecurityUser' ) );
					$c->add ( GroupgalleryPeer::PUB, 3, Criteria::LESS_THAN );
					$cn = GroupgalleryPeer::doCount ( $c );
					if ($cn == 0 or sfConfig::get('app_gallery_autoapprove')==true) {
						
						if(sfConfig::get('app_use_payment_add_gallery')!='true')
						{			
							$u->setAccount ( $u->getAccount () - sfConfig::get ( 'app_cost_gallery_show' ) );
							$u->save ();
							
							$pa = new Payment ( );
							$pa->setUserId ( $this->getUser ()->getAttribute ( 'user_id', null, 'sfGuardSecurityUser' ) );
							$pa->setPaymentId ( $this->getUser ()->getAttribute ( 'user_id', null, 'sfGuardSecurityUser' ) );
							$pa->setLevelId ( 9 );
							$pa->setSumma ( sfConfig::get ( 'app_cost_gallery_show' ) );
							$pa->setDirection ( 0 );
							$pa->save ();
							$this->getUser ()->setFlash ( 'message', 'За создание фотогалереи с вашего счета снято 5 кредитов' );
						}
						$g->save ();
						$this->redirect ( '@gallery_edit?id=' . $g->getId () );
					} else {
						$this->getUser ()->setFlash ( 'error', 'Вы не можете создать галерею пока существуют неутвержденные галереи.' );
						$this->redirect ( '@my_photos' );
					}
				
				}
			
			}
			$this->redirect ( '@gallery_edit?id=' . $g->getId () );
		
		}
		if ($this->getUser ()->getProfile ()->getGender () == 'w') {
			
			
			$g = new Groupgallery ( );
			$g->setUserId ( $this->getUser ()->getAttribute ( 'user_id', null, 'sfGuardSecurityUser' ) );
			$g->setLogoId ( 1 );
			if(sfConfig::get('app_gallery_autoapprove')=='true')
				{
					$g->setPub ( 3 );
					
				}
				else {
					
					$g->setPub ( 1 );
				}		
			$g->setCount ( 0 );
			$c = new Criteria ( );
			$c->add ( GroupgalleryPeer::USER_ID, $this->getUser ()->getAttribute ( 'user_id', null, 'sfGuardSecurityUser' ) );
			$cnt = GroupgalleryPeer::doCount ( $c );
			
			$g->setMaxPhotos ( sfConfig::get('app_last_gallery_max') );
			$g->setType ( true );
			
			$c = new Criteria ( );
			$c->add ( GroupgalleryPeer::USER_ID, $this->getUser ()->getAttribute ( 'user_id', null, 'sfGuardSecurityUser' ) );
			$c->add ( GroupgalleryPeer::PUB, 3, Criteria::LESS_THAN );
			$cn = GroupgalleryPeer::doCount ( $c );
			if ($cn == 0) {
				$g->save ();
			} else {
				$this->getUser ()->setFlash ( 'error', 'Вы не можете создать галерею пока существуют неутвержденные галереи.' );
				$this->redirect ( '@my_photos' );
			}
			$this->redirect ( '@gallery_edit?id=' . $g->getId () );
		}
		

	
	}
	
	public function executeEditgallery(sfWebRequest $request) {

		$this->setDecorator();


	        $ph = new Gallery ( );
		$ph->setGroupId ( 1 );
		$ph->setUserId ( $this->getUser()->getProfile()->getId() );
		$this->gallery = GroupgalleryPeer::retrieveByPK ( $request->getParameter ( 'id' ) );
		$this->form = new GalleryForm ( $ph );
		if ($request->isMethod ( 'post' ))

		{
			$this->form->bind ( $request->getParameter ( 'gallery' ), $request->getFiles ( 'gallery' ) );
			if ($this->form->isValid ()) {

				$this->form->save ();
				$this->redirect ( '@gallery_edit?id=' . $this->form->getObject ()->getGroupId () );
			}

		}



		$c = new Criteria ( );
		$c->add ( GalleryPeer::USER_ID, $this->getUser ()->getAttribute ( 'user_id', null, 'sfGuardSecurityUser' ) );
		$c->addAnd ( GalleryPeer::GROUP_ID, 1 );


		$this->photos = GalleryPeer::doSelect($c);


		///Кидаем пользователя в layout
	     $this->getRequest()->setAttribute('v', $this->getUser()->getProfile());
		////
	}
	
	public function executeListgallery(sfWebRequest $request) {
		 $this->setDecorator();
	    	////Проверка на регистрацию
		  	if(!$this->getUser()->isAuthenticated())
		  	{
		  	 $this->getUser ()->setFlash ( 'error', 'Только для зарегистрированных пользователей' );
		  	 $this->redirect('@registration');
		  	}
		
		$this->user = sfGuardUserPeer::retrieveByPK ( $request->getParameter ( 'id' ) );
		$this->forward404Unless ( $this->user );
		
		$c = new Criteria ( );
		$c->add ( GalleryPeer::USER_ID, $this->user->getId () );
		$this->gallery = GalleryPeer::doSelect($c);
			
		
		/*
		     *  Передаем пользователя в layout
		     * 
		     */
		$this->getRequest ()->setAttribute ( 'v', $this->user );
	}
	
	public function executeShowgallery(sfWebRequest $request) {
		
		$this->setDecorator();
		$this->gallery = GroupgalleryPeer::retrieveByPK ( $request->getParameter ( 'id' ) );
		$this->forward404Unless ( $this->gallery );
		$this->user = $this->gallery->getsfGuardUser ();
		$u = $this->getUser ()->getProfile ();
		
		///проверка на фаворит для бабы
		if ($u->getGender () == 'w' and $this->user->getGender () == 'm' and sfConfig::get ( 'app_denite_show_gallery_all' )==true) {
			$c = new Criteria ( );
			$c->add ( FavoritePeer::FAV_ID, $u->getId () );
			$c->add ( FavoritePeer::USER_ID, $this->user->getId () );
			$cnt = FavoritePeer::doCount ( $c );
			if ($cnt == 0) {
				$this->getUser ()->setFlash ( 'error', 'Вы не находитесь среди его друзей' );
				$this->redirect ( '@user_gallery_list?id=' . $this->user->getId () );
			}
		}
		///
		

		if ($this->user->getIsVip () == 'true') {
			
			if ($u->getAccount () < sfConfig::get ( 'app_cost_gallery_show' )) {
				$this->getUser ()->setFlash ( 'error', 'У вас недостаточно средств на счете' );
				$this->redirect ( '@account' );
			} else {
				$u->setAccount ( $u->getAccount () - sfConfig::get ( 'app_cost_gallery_show' ) );
				$u->save ();
				
				$pa = new Payment ( );
				$pa->setUserId ( $this->getUser ()->getAttribute ( 'user_id', null, 'sfGuardSecurityUser' ) );
				$pa->setPaymentId ( $this->getUser ()->getAttribute ( 'user_id', null, 'sfGuardSecurityUser' ) );
				$pa->setLevelId ( 5 );
				$pa->setSumma ( sfConfig::get ( 'app_cost_gallery_show' ) );
				$pa->setDirection ( 0 );
				$pa->save ();
				
				$this->getUser ()->setFlash ( 'message', 'За просмотр фотогалереи с вашего счета снято 2 кредита' );
			
			}
		}
		
		///Выбираем фотки
		$c = new Criteria ( );
		$c->add ( GalleryPeer::GROUP_ID, $this->gallery->getId () );
		$pager = new sfPropelPager ( 'Gallery', sfConfig::get ( 'app_group_gallery_perpage' ) );
		$pager->setCriteria ( $c );
		$pager->setPeerMethod ( 'doSelect' );
		$pager->setPage ( $this->page );
		$pager->init ();
		$this->photos = $pager;
		
		//// Выбираем галереи 
		

		$c = new Criteria ( );
		$c->add ( GroupgalleryPeer::USER_ID, $this->gallery->getUserId () );
		$c->addAnd ( GroupgalleryPeer::ID, $this->gallery->getId (), Criteria::NOT_EQUAL );
		$pager = new sfPropelPager ( 'Groupgallery', sfConfig::get ( 'app_group_gallery_perpage' ) );
		$pager->setCriteria ( $c );
		$pager->setPeerMethod ( 'doSelect' );
		$pager->setPage ( $this->page );
		$pager->init ();
		$this->gallerys = $pager;
		
		$this->getRequest ()->setAttribute ( 'v', $this->user );
	
	}
	
	public function executeGroup_gallery_delete(sfWebRequest $request) {
		$this->setDecorator();
		$this->gallery = GroupgalleryPeer::retrieveByPK ( $request->getParameter ( 'id' ) );
		$this->forward404Unless ( $this->gallery );
		$this->gallery->delete ();
	    ///Кидаем пользователя в layout
	     $this->getRequest()->setAttribute('v', $this->getUser()->getProfile());
		////
	}
	
	public function executePhoto_delete(sfWebRequest $request) {
		
		$this->photo = GalleryPeer::retrieveByPK ( $request->getParameter ( 'id' ) );
		$group_id = $this->photo->getGroupId ();
		$this->forward404Unless ( $this->photo );
		if ($this->photo->getUserId () == $this->getUser ()->getAttribute ( 'user_id', null, 'sfGuardSecurityUser' ))
			$this->photo->delete ();
		$this->redirect ( '@gallery_edit?id=' . $group_id );
	
	}
	
	public function executeSet_logo(sfWebRequest $request) {
		
		$this->photo = GalleryPeer::retrieveByPK ( $request->getParameter ( 'idp' ) );
		$this->group = GroupgalleryPeer::retrieveByPK ( $request->getParameter ( 'idg' ) );
		$this->forward404Unless ( $this->photo );
		$this->forward404Unless ( $this->group );
		
		$this->group->setLogoId ( $request->getParameter ( 'idp' ) );
		$this->group->save ();
		$this->redirect ( '@gallery_edit?id=' . $request->getParameter ( 'idg' ) );
	
	}
	
	public function executeWait_approwe(sfWebRequest $request) {
		
		$g = GroupgalleryPeer::retrieveByPK ( $request->getParameter ( 'id' ) );
		$g->setPub ( 2 );
		$g->save ();
		$this->getUser ()->setFlash ( 'message', 'Галерея отослана на утверждение администратору' );
		$this->redirect ( '@gallery_edit?id=' . $g->getId () );
	}
	
	/*
	 *  Опубликование галлереи
	 */
	public function executeSetpub(sfWebRequest $request) {
		
		$g = GroupgalleryPeer::retrieveByPK($request->getParameter('id'));
		
		if($request->getParameter('pub')=='true')
		{
			$g->setPub(3);
		}
		else {
			
			 $g->setPub(2);
		}
		$g->save();
		$this->redirect ( '@my_photos' );
	}
	
	
	
	public function setDecorator()
	{
		
		$module = $this->getRequest()->getParameter('module');
		$action = $this->getRequest()->getParameter('action');
		
		$path_layout = sfConfig::get('sf_app_template_dir').'/layouts/'.sfConfig::get('app_name').'/'.$module.'.php';
		$path_template = sfConfig::get('sf_app_module_dir').'/'.$module.'/templates/'.sfConfig::get('app_name').'/'.$action.'Success.php';
		if(file_exists($path_layout))
		{ $l = 'layouts/'.sfConfig::get('app_name').'/'.$module; }
		else
		{ $l = sfConfig::get('app_name').'_layout'; }
		if(file_exists($path_template))
		{ $t = sfConfig::get('app_name').'/'.$action; }
		else
		{ $t = $action; }
			
	/*
     * Установка layout
     */	
			$this->setLayout ( $l );
		
     /*
     *  Устанавливаем шаблон
     */
		
			$this->setTemplate ( $t );
	}
	
	
}
